﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Reflection;
using System.Web.UI.WebControls;

namespace StoragePeriod.Common
{
    public static class Extension
    {
        #region 扩展方法


        public static string EToString(this object item)
        {
            if (item == null)
                return string.Empty;
            else
                return item.ToString().Trim();
        }

        public static string StrFilter(this string obj)
        {
            string temp = obj.EToString();
            temp = temp.Replace("+", "").Replace("-", "").Replace(",", "").Replace("-", "").Replace("↑", "").Replace("↓", "");
            return temp;
        }

        /// <summary>
        /// 取值通用方法
        /// </summary>
        public static object TryGetValue(this object obj, string field)
        {
            if (obj == null) return string.Empty;

            PropertyInfo fieldPro = obj.GetType().GetProperty(field);
            if (fieldPro != null)
                return fieldPro.GetValue(obj, null);

            return string.Empty;
        }

        public static object GetCellText(this GridViewRow row, string field)
        {
            var fieldCells = row.Controls.AllOfType<DataControlFieldCell>();
            return fieldCells.FirstOrDefault(p => p.ContainingField.HeaderText == field).Text;
        }

        public static bool TryParseToBool(this object item)
        {
            if (item == null) return false;

            if (item.ToString() == "1")
                return true;
            if (item.ToString() == "0")
                return false;

            bool temp = false;
            bool.TryParse(item.EToString(), out temp);
            return temp;
        }

        public static double TryGetRound(this string str, int round)
        {
            double temp1 = str.TryParseToDouble();
            return Math.Round(temp1, round);
        }

        public static DateTime TryParseToDateTime(this string item)
        {
            try
            {
                string newDateTime = item.Insert(6, "/").Insert(4, "/");
                return Convert.ToDateTime(newDateTime);
            }
            catch
            {
                DateTime n;
                if (DateTime.TryParse(item, out n))
                {
                    return n;
                }

                return DateTime.Now;
            }
        }

        public static int TryParseToInt(this string item)
        {
            if (string.IsNullOrEmpty(item)) return -1;
            int temp = -1;
            bool ok = int.TryParse(item, out temp);
            if (!ok)
            {
                temp = (int)Math.Round(item.TryParseToDouble(), 0);
            }

            return temp;
        }
        public static double TryParseToDouble(this string item)
        {
            if (string.IsNullOrEmpty(item)) return 0;

            double b;
            if (double.TryParse(item, out b)) { return b; }

            return -1;
        }
        public static decimal TryParseToDecimal(this string item)
        {
            if (string.IsNullOrEmpty(item)) return 0;
            item = item.StrFilter();
            decimal b;
            if (decimal.TryParse(item, out b)) { return b; }

            return -1;
        }
        public static DateTime TryParseToDateTime(this DateTime? item)
        {
            if (item.HasValue)
            {
                return item.Value;
            }

            return DateTime.Now;
        }

        public static string FormatUserString(this object item)
        {
            if (item == null)
                return string.Empty;
            else
            {
                if (item.ToString().IndexOf('#') != -1)
                    return item.ToString().Split('#')[1];
                else
                    return item.ToString();
            }
        }
        public static string FormatUserIDString(this object item)
        {
            if (item == null)
                return string.Empty;
            else
            {
                if (item.ToString().IndexOf('#') != -1)
                    return item.ToString().Split('#')[0].Replace(";", "");
                else
                    return item.ToString();
            }
        }

        /// <summary>
        /// 判断字符串为空或NULL
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string self)
        {
            return string.IsNullOrEmpty(self);
        }

        /// <summary>
        /// 判断字符串不非空非NULL
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool NotNullOrEmpty(this string self)
        {
            return !string.IsNullOrEmpty(self);
        }

        public static void OKAndCloseDlg(this Page self)
        {
            self.OKAndCloseDlg(string.Empty);
        }

        public static void Alert(this Page self, string retVal)
        {
            var script = string.Format("alert('{0}');", retVal);
            
            
            self.ClientScript.RegisterClientScriptBlock( self.GetType(), "alertMsg", script, true);
        }

        public static void AlertAndClose(this Page self, string retVal)
        {
            var script = string.Format("alert('{0}');window.top.sp.page.close();", retVal);

            self.ClientScript.RegisterClientScriptBlock(self.GetType(), "alertMsg", script, true);
        }

        public static void OKAndCloseDlg(this Page self, string retVal)
        {
            var script = "<script type='text/javascript'>";
            script += "    function closeDlg(){";
            script += "    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, '" + retVal + "');";
            script += "    }";
            script += "    ExecuteOrDelayUntilScriptLoaded(closeDlg, 'sp.js');";
            script += "</script>";
            self.ClientScript.RegisterClientScriptBlock(self.GetType(), "closeDlg", script);
        }

        public static void CancelAndCloseDlg(this Page self)
        {
            var script = "<script type='text/javascript'>";
            script += "    function closeDlg(){";
            script += "    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, '');";
            script += "    }";
            script += "    ExecuteOrDelayUntilScriptLoaded(closeDlg, 'sp.js');";
            script += "</script>";



            if (string.IsNullOrEmpty(self.Request["IsDlg"]))
            {
                self.ClientScript.RegisterClientScriptBlock(self.GetType(), "closePage", "<script>window.close();</script>");
            }
            else
            {
                self.ClientScript.RegisterClientScriptBlock(self.GetType(), "closeDlg", script);
            }
        }

        public static IEnumerable<TreeNode> AllNodes(this TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                foreach (var no in node.ChildNodes.AllNodes())
                    yield return no;

                yield return node;
            }
        }

        public static IEnumerable<TreeNode> CurrentNodes(this TreeNodeCollection nodes)
        {
            foreach (TreeNode item in nodes)
            {
                yield return item;
            }
        }

        #endregion
    }
}